<template>
	<div class="UpdatePic">
		<button class="btn" @click="Update()">更改头像</button>
		<el-upload class="avatar-uploader" :multipe="false"
		            :show-file-list="true" :auto-upload="false"
		            :before-upload="beforeAvatarUpload" 
		            :file-list="fileList"                            
		            :on-change="handleChange"
		            action = "uploadAction"
		            list-type="picture"
		            accept="image/jpg,image/jpeg">
		            <img v-if="imageUrl" :src="`${$ip}/api/public/showimg/${imageUrl}`" class="avatar">
		            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
		     </el-upload> 
	</div>
</template>

<script>
	export default{
		name:'UpdatePic',
		data() {
			return{
				fileList: [],
				imageUrl:'',
			}
		},
		methods:{
			handleChange: function(file, fileList) {
			     this.fileList = fileList;
				 console.log(this.fileList);
			},
			beforeAvatarUpload(file) {
			    const isJPG = file.type === 'image/jpeg';
			    const isLt2M = file.size / 1024 / 512;
					
			    if (!isJPG) {
			        this.$message.error('上传图片只能是 JPG 格式!');
			    }
			    if (!isLt2M) {
			        this.$message.error('上传图片大小不能超过 0.5MB!');
			    }
			    return isJPG && isLt2M;
			},
			Update(){
				let fd  = new FormData();
				let fs = this.fileList;
				if(fs.length==0){
					this.$message({
						message:'请选择头像',
						type:'error',
					})
					return;
				}
				fd.append("mypic", fs[0].raw);
				this.$postf("/api/user/updatePic",fd).then((resp)=>{
					this.imageUrl = resp.data.data;
					this.$store.state.img = this.imageUrl;
					console.log(resp.data);
					this.$message({
						message:resp.data.msg,
						type:'success',
					})
				})
			}
		}
	}
</script>

<style scoped>
	.UpdatePic{

		margin: 20px auto;
	}
	.avatar-uploader:hover {
	  border-color: #409EFF;
	}
	.avatar-uploader-icon {
			border: 2px #000000 dotted;
			border-radius: 8px;
	  font-size: 40px;
	  color: #8c939d;
	  width: 400px;
	  height: 400px;
	  line-height: 400px;
	  text-align: center;
	}
	.avatar {
	  width: 178px;
	  height: 178px;
	  display: block;
	}
	.btn{
		width: 100%;
		height: 30px;
		background-color: crimson;
		color: white;
		border: none;
		outline: none;
		border-radius: 5px;
	}
</style>